<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        @enter="handleQuery"
        label-width="65px"
      >
        <el-form-item label="任务名称" prop="nmapName">
          <common-input
            v-model="queryParams.nmapName"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="扫描方式" prop="scanType">
          <el-select v-model="queryParams.scanType">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="主机扫描" :value="'0'"></el-option>
            <el-option label="端口扫描" :value="'1'"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="IP段" prop="nmapIps">
          <common-input
            v-model="queryParams.nmapIps"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="端口段" prop="nmapPorts">
          <common-input
            v-model="queryParams.nmapPorts"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->

        <el-form-item label="执行周期" prop="jobCycle">
          <el-select v-model="queryParams.jobCycle" filterable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in executionCycleTypeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="启用" :value="0"></el-option>
            <el-option label="停用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>

    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['nmap:task:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="ids.length < 1"
          @click="handleDelete"
          v-hasPermi="['nmap:task:remove']"
          >批量删除
        </el-button>
      </el-col>
    </el-row>

    <common-table
      v-loading="loading"
      slot="content"
      :data="assetsScanList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="任务名称"
        align="left"
        prop="nmapName"
        show-overflow-tooltip
      />

      <!-- <el-table-column
        label="扫描方式"
        align="left"
        prop="scanTypeString"
        show-overflow-tooltip
      /> -->
      <el-table-column
        label="IP段"
        align="left"
        prop="nmapIps"
        show-overflow-tooltip
      />
      <!-- <el-table-column
        label="端口段"
        align="left"
        prop="nmapPorts"
        show-overflow-tooltip
      /> -->
      <el-table-column
        label="执行周期"
        align="left"
        prop="jobCycleString"
        show-overflow-tooltip
      />
      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        width="180"
      />
      <el-table-column label="状态" align="left" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="success">启用</el-tag>
          <el-tag v-if="scope.row.status === 1" type="danger">停用</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="left" width="180px">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleExeNow(scope.row)"
            v-if="scope.row.status === 0"
            v-hasPermi="['nmap:task:scanNow']"
            >立即执行
          </el-button>

          <el-button
            type="text"
            @click="handleHistory(scope.row)"
            v-hasPermi="['nmap:task:getHis']"
            >历史记录
          </el-button>

          <el-dropdown @command="handleMoreTools(scope.row, $event)">
            <span
              class="el-dropdown-link"
              style="cursor: pointer; margin-left: 8px; font-size: 12px"
              v-hasPermi="[
                'nmap:task:rescan',
                'nmap:task:edit',
                'nmap:task:remove',
              ]"
            >
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" class="size">
              <!-- <el-dropdown-item command="detail"> 详情 </el-dropdown-item> -->
              <el-dropdown-item
                command="changeStatus"
                v-hasPermi="['nmap:task:rescan']"
              >
                <div :disabled="scope.row.isDisabledForShake">
                  <span v-if="scope.row.status == 1">启用</span>
                  <span v-if="scope.row.status == 0">停用</span>
                </div>
              </el-dropdown-item>
              <el-dropdown-item command="edit" v-hasPermi="['nmap:task:edit']">
                编辑
              </el-dropdown-item>
              <el-dropdown-item
                command="delete"
                v-hasPermi="['nmap:task:remove']"
                >删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <History
      ref="history"
      v-if="detailShow"
      @back="detailShow = false"
      :detailId="detailId"
    ></History>
    <scan-add ref="scanAdd" @submitForm="submitForm"></scan-add>

    <scan-detail ref="scanDetail"></scan-detail>
  </common-list>
</template>

<script>
import {
  fetchList,
  assetsScanDelete,
  statusUpdate,
  scanNow,
} from "@/api/analysisCenter/assetsScan";
import ScanAdd from "./components/scanAdd.vue";
import ScanDetail from "@/views/analysisCenter/assetsScan/components/scanDetail.vue";
import History from "./components/history.vue";
import BaseList from "@/mixins/BaseList";
import { getJobCycleString } from "@/utils/cycleFun";
import { CYCLESHORTARR } from "@/utils/constant";

export default {
  mixins: [BaseList],
  components: {
    History,
    ScanAdd,
    ScanDetail,
  },
  data() {
    return {
      ids: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nmapName: null,
        scanType: null,
        nmapIps: null,
        // nmapPorts: null,
        status: null,
        type: "DATASCAN",
        jobCycle: null,
      },
      total: 0,
      assetsScanList: [],
      loading: false,
      detailShow: false,
      detailId: null,
      executionCycleTypeArr: CYCLESHORTARR,
    };
  },
  created() {
    this.getList();
  },

  methods: {
    getList() {
      this.loading = true;
      fetchList(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.assetsScanList = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                scanTypeString: c.scanType === "0" ? "主机扫描" : "端口扫描",
                isDisabledForShake: false,
                jobCycleString: getJobCycleString(c, "执行"),
              });
              return r;
            }, []);

            this.total = res.total;
          } else {
            this.assetsScanList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .catch(() => {
          this.assetsScanList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleAdd(row) {
      if (row.id && row.status === 0) {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
        return;
      }
      this.$refs.scanAdd.show(row ? { ...row } : {});
    },

    //更多
    handleMoreTools(row, operate) {
      //详情
      if (operate === "detail") {
        this.handleView(row);
      }

      //启用/停用
      if (operate === "changeStatus") {
        this.changeStatus(row);
      }

      //编辑
      if (operate === "edit") {
        this.handleAdd(row);
      }

      //删除
      if (operate === "delete") {
        this.handleDelete(row);
      }
    },

    //详情
    handleView(row) {
      this.$refs.scanDetail.show(row);
    },

    //启用/停用
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        statusUpdate({
          status: row.status === 1 ? 0 : 1,
          id: row.id,
        })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("操作成功");
              resolve(res);
              this.assetsScanList.find((item) => {
                return item.id === row.id;
              }).status = row.status === 1 ? 0 : 1;
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg);
              reject();
            }
          })
          .catch(() => reject());
      });
    },

    //立即执行
    handleExeNow(row) {
      scanNow({ id: row.id }).then((res) => {
        if (res && res.code === 200) {
          this.$GlobalSuccessMessage("操作成功");
          this.getList();
        } else {
          this.$GlobalErrorConfirm("操作失败", res.msg);
        }
      });
    },

    handleHistory(row) {
      this.detailId = row.id;
      this.detailShow = true;
    },

    handleDelete(row) {
      const ids = row.id || this.ids.join(",");

      if (row && row.status === 0) {
        this.$GlobalErrorConfirm("警告", "启用状态下不允许删除");
        return;
      }

      let enableStatus = this.assetsScanList.find((v) => {
        return this.ids.includes(v.id) && v.status === 0;
      });

      if (enableStatus) {
        this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        return;
      }

      this.$GlobalDeleteConfirm()
        .then(() => {
          assetsScanDelete({ ids }).then((res) => {
            if (res && res.code == 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.queryParams.pageNum > 1 &&
                ids.split(",").length === this.assetsScanList.length
              ) {
                this.queryParams.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },

    submitForm() {
      this.getList();
    },

    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dropdown-link {
  color: var(--theme-color);
}
</style>
